import 'package:flutter/material.dart';
import 'package:gluz/app/common/aliyun_oss.dart';
import 'package:gluz/app/common/resource_picker_sheet.dart';
import 'package:gluz/app/utils/toast_util.dart';

/// 阿里云OSS上传示例
class AliyunOSSExample extends StatefulWidget {
  const AliyunOSSExample({Key? key}) : super(key: key);

  @override
  State<AliyunOSSExample> createState() => _AliyunOSSExampleState();
}

class _AliyunOSSExampleState extends State<AliyunOSSExample> {
  double _uploadProgress = 0.0;
  String _uploadStatus = '准备上传';
  String? _uploadedUrl;
  String? _errorMessage;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('阿里云OSS上传示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 进度条
            LinearProgressIndicator(
              value: _uploadProgress / 100,
              backgroundColor: Colors.grey[300],
              valueColor: AlwaysStoppedAnimation<Color>(
                _uploadProgress == 100 ? Colors.green : Colors.blue,
              ),
            ),
            const SizedBox(height: 8),
            
            // 进度文本
            Text(
              '上传进度: ${_uploadProgress.toStringAsFixed(1)}%',
              style: const TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 8),
            
            // 状态文本
            Text(
              _uploadStatus,
              style: TextStyle(
                fontSize: 14,
                color: _uploadProgress == 100 ? Colors.green : Colors.orange,
              ),
            ),
            const SizedBox(height: 16),
            
            // 上传按钮
            ElevatedButton(
              onPressed: _uploadProgress == 0 ? _uploadImage : null,
              child: const Text('上传图片'),
            ),
            const SizedBox(height: 8),
            
            ElevatedButton(
              onPressed: _uploadProgress == 0 ? _uploadVideo : null,
              child: const Text('上传视频'),
            ),
            const SizedBox(height: 8),
            
            ElevatedButton(
              onPressed: _uploadProgress == 0 ? _uploadDocument : null,
              child: const Text('上传文档'),
            ),
            const SizedBox(height: 8),
            
            ElevatedButton(
              onPressed: _uploadProgress == 0 ? _uploadAvatar : null,
              child: const Text('上传头像'),
            ),
            const SizedBox(height: 8),
            
            ElevatedButton(
              onPressed: _uploadProgress == 0 ? _batchUpload : null,
              child: const Text('批量上传'),
            ),
            const SizedBox(height: 16),
            
            // 结果显示
            if (_uploadedUrl != null) ...[
              const Text(
                '上传成功:',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: SelectableText(_uploadedUrl!),
              ),
            ],
            
            if (_errorMessage != null) ...[
              const SizedBox(height: 16),
              Text(
                '上传失败: $_errorMessage',
                style: const TextStyle(color: Colors.red),
              ),
            ],
            
            const SizedBox(height: 16),
            
            // 重置按钮
            ElevatedButton(
              onPressed: _reset,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.grey,
              ),
              child: const Text('重置'),
            ),
          ],
        ),
      ),
    );
  }

  /// 上传图片示例
  Future<void> _uploadImage() async {
    _reset();
    setState(() {
      _uploadStatus = '开始上传图片...';
    });

    try {
      // 模拟文件路径，实际使用时需要从文件选择器获取
      const String filePath = '/path/to/image.jpg';
      
      final result = await AliyunOSSUploader.uploadImage(
        filePath: filePath,
        onProgress: (sent, total) {
          setState(() {
            _uploadProgress = (sent / total * 100);
            _uploadStatus = '上传中... ${_uploadProgress.toStringAsFixed(1)}%';
          });
        },
      );

      if (result.isSuccess) {
        setState(() {
          _uploadedUrl = result.url;
          _uploadStatus = '上传完成';
        });
      } else {
        setState(() {
          _errorMessage = result.errorMessage;
          _uploadStatus = '上传失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _uploadStatus = '上传异常';
      });
    }
  }

  /// 上传视频示例
  Future<void> _uploadVideo() async {
    _reset();
    setState(() {
      _uploadStatus = '开始上传视频...';
    });

    try {
      const String filePath = '/path/to/video.mp4';
      
      final result = await AliyunOSSUploader.uploadVideo(
        filePath: filePath,
        onProgress: (sent, total) {
          setState(() {
            _uploadProgress = (sent / total * 100);
            _uploadStatus = '上传中... ${_uploadProgress.toStringAsFixed(1)}%';
          });
        },
      );

      if (result.isSuccess) {
        setState(() {
          _uploadedUrl = result.url;
          _uploadStatus = '上传完成';
        });
      } else {
        setState(() {
          _errorMessage = result.errorMessage;
          _uploadStatus = '上传失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _uploadStatus = '上传异常';
      });
    }
  }

  /// 上传文档示例
  Future<void> _uploadDocument() async {
    _reset();
    setState(() {
      _uploadStatus = '开始上传文档...';
    });

    try {
      const String filePath = '/path/to/document.pdf';
      
      final result = await AliyunOSSUploader.uploadDocument(
        filePath: filePath,
        onProgress: (sent, total) {
          setState(() {
            _uploadProgress = (sent / total * 100);
            _uploadStatus = '上传中... ${_uploadProgress.toStringAsFixed(1)}%';
          });
        },
      );

      if (result.isSuccess) {
        setState(() {
          _uploadedUrl = result.url;
          _uploadStatus = '上传完成';
        });
      } else {
        setState(() {
          _errorMessage = result.errorMessage;
          _uploadStatus = '上传失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _uploadStatus = '上传异常';
      });
    }
  }

  /// 上传头像示例
  Future<void> _uploadAvatar() async {
    _reset();
    setState(() {
      _uploadStatus = '开始上传头像...';
    });

    try {
      const String filePath = '/path/to/avatar.jpg';
      const String userId = 'user123';
      
      final result = await AliyunOSSUploader.uploadAvatar(
        filePath: filePath,
        userId: userId,
        onProgress: (sent, total) {
          setState(() {
            _uploadProgress = (sent / total * 100);
            _uploadStatus = '上传中... ${_uploadProgress.toStringAsFixed(1)}%';
          });
        },
      );

      if (result.isSuccess) {
        setState(() {
          _uploadedUrl = result.url;
          _uploadStatus = '上传完成';
        });
      } else {
        setState(() {
          _errorMessage = result.errorMessage;
          _uploadStatus = '上传失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _uploadStatus = '上传异常';
      });
    }
  }

  /// 批量上传示例
  Future<void> _batchUpload() async {
    _reset();
    setState(() {
      _uploadStatus = '开始批量上传...';
    });

    try {
      const List<String> filePaths = [
        '/path/to/file1.jpg',
        '/path/to/file2.png',
        '/path/to/file3.pdf',
      ];
      
      final results = await AliyunOSSUploader.uploadFiles(
        filePaths: filePaths,
        onProgress: (currentIndex, totalFiles) {
          setState(() {
            _uploadProgress = (currentIndex / totalFiles * 100);
            _uploadStatus = '批量上传中... ${currentIndex + 1}/$totalFiles';
          });
        },
      );

      // 检查所有文件是否上传成功
      final successCount = results.where((r) => r.isSuccess).length;
      final failedCount = results.length - successCount;

      if (failedCount == 0) {
        setState(() {
          _uploadedUrl = '所有文件上传成功 (${results.length}个文件)';
          _uploadStatus = '批量上传完成';
        });
      } else {
        setState(() {
          _errorMessage = '上传完成，成功: $successCount, 失败: $failedCount';
          _uploadStatus = '批量上传部分失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _uploadStatus = '批量上传异常';
      });
    }
  }

  /// 重置状态
  void _reset() {
    setState(() {
      _uploadProgress = 0.0;
      _uploadStatus = '准备上传';
      _uploadedUrl = null;
      _errorMessage = null;
    });
  }
}

/// 使用扩展方法的示例
class AliyunOSSExampleWithExtension {
  /// 使用扩展方法上传文件
  static Future<void> uploadWithExtension() async {
    const String filePath = '/path/to/file.jpg';
    
    // 使用扩展方法上传图片
    final result = await filePath.uploadAsImage(
      onProgress: (sent, total) {
        final progress = (sent / total * 100).round();
        print('上传进度: $progress%');
      },
    );
    
    if (result.isSuccess) {
      print('上传成功: ${result.url}');
    } else {
      print('上传失败: ${result.errorMessage}');
    }
  }
} 